package com.tanhua.admin.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ManageService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    //查询所有用户
    public PageResult findUsers(Integer page, Integer pagesize) {
        //1、调用API分页查询，Ipage对象
        IPage iPage = userInfoApi.findAll(page,pagesize);
        //2、转化成PageResult
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    public UserInfo findUserById(Long id) {
        return userInfoApi.findById(id);
    }

    //查询当前用户发布的所有视频
    public PageResult findVideosByUserId(Integer page, Integer pagesize, Long userId) {
        //1、调用API查询用户发布的所有视频  PageResult 《数据列表和总数》
        PageResult result = videoApi.findAll(page,pagesize,userId);
        if(result == null ) {
            return new PageResult();
        }
        //2、将数据中list<Video>转化成  List<VideoVo>
        UserInfo info = userInfoApi.findById(userId);
        List<Video> items = (List<Video>) result.getItems();
        List<VideoVo> vos = new ArrayList<>();
        for (Video item : items) {
            VideoVo vo = VideoVo.init(info, item);
            vos.add(vo);
        }
        //3、返回
        result.setItems(vos);
        return result;
    }

    //查询当前动态列表
    public PageResult findMovementByUserId(Integer page, Integer pagesize, Long uid, Integer state) {
        //1、调用API查询列表 PageResult 《数据列表和总数》
        PageResult result = movementApi.findAll(page,pagesize,uid,state);
        if(result == null || result.getItems()== null) {
            return new PageResult();
        }
        //2、将数据中List<Movement> 转化成  List<MovementVo>
        List<Movement> items = (List<Movement>) result.getItems();
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement item : items) {
            UserInfo info = userInfoApi.findById(item.getUserId());
            MovementsVo vo = MovementsVo.init(info, item);
            vos.add(vo);
        }
        //3、返回
        result.setItems(vos);
        return result;
    }
}
